package ProcessManager;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class ProcessManager
{
	private List<Process> ProcessList;
	private static ProcessManager ref;

	/**
	 * Creates a ProcessManager Singleton
	 * 
	 * @return ProcessManager Object
	 */
	public static ProcessManager getInstance()
	{
		if (ref == null)
			// it's ok, we can call this constructor
			ref = new ProcessManager();
		return ref;
	}

	private ProcessManager()
	{
		ProcessList = new ArrayList<Process>();
	}

	public void destroy()
	{
	}

	public void Attach(Process newProcess)
	{
		ProcessList.add(newProcess);
	}

	public boolean IsEmpty()
	{
		return ProcessList.isEmpty();
	}

	public boolean IsProcessActive(String name)
	{
		return ProcessList.contains(name);
	}

	public void UpdateProcesses(int milliseconds)
	{
		if (!IsEmpty())
		{
			ListIterator<Process> Itor = ProcessList.listIterator();
			Process activeProcess = new Process();
			while (Itor.hasNext())
			{
				// retrieves the object and advances iterator
				activeProcess = Itor.next();
				if (activeProcess.GetKill())
				{
					if (activeProcess.GetNext() != null)
					{
						ProcessList.remove(activeProcess);
						activeProcess.GetNext().InitializeProcess();
						Attach(activeProcess.GetNext());
					}
				} else
				{
					activeProcess.UpdateProcess(milliseconds);
				}
			}
		}
	}
}
